<link rel="stylesheet" href="/modules/leader/css/style.css">

<div class="holiday look">
    <p style="margin:0;padding:10px;display:inline-block;">节假日</p>
    <input type="button" value="编辑" id="hol_btn" class="time_setting_edit">
    <p style="color: darkgray; margin-bottom: 0; font-size: 12px; margin-left: 10px">＊节假日不记录考勤</p>
    <div style="border-bottom: 1px solid #cccccc;height:5px;"></div>
    <div style="padding: 10px;" id="look_festivals">
        <div style="float:left;padding-bottom:10px;width:100px;">国庆节</div>
        <div style="display:inline-block;margin-left:40px;float:left;">2016-10-1<div style="width:40px;display:inline-block;"></div>至<div style="width:40px;display:inline-block;"></div>2016-10-7</div>
        <div style="clear:both;"></div>
    </div>
</div>
<div class="holiday convert">
    <p style="margin:0;padding:10px;display:inline-block;">节假日</p>
    <input type="button" value="保存" id="s2_btn" class="time_setting_edit">
    <div style="border-bottom: 1px solid #cccccc;height:15px;"></div>
    <div style="height:15px;"></div>

    <ul class="sui-tag" id="hol_tags" style="margin:10px;">
        <li>清明节</li>
        <li>端午节</li>
        <li>国庆节</li>
        <li>元旦</li>
        <li>劳动节</li>
        <li>中秋节</li>
    </ul>
    <form class="sui-form" style="display: none;">
        <input type="text" value="2014-03-02 12:48" id="unvisiablePicker">
    </form>
    <div class="hol_lump" id="edit_hol_list" style="padding-left: 10px">

        <div class="hol_lump-item" >
            <input type="text"  value="国庆节" style="width:70px;height:18px;padding:2px 4px;border: 1px solid #cccccc;font-size: 12px;">

            <form class="sui-form demo8" style="margin-left: 20px;display: inline-block;">
                <input type="text" value="2014-03-02 12:48">
            </form>
            至
            <form class="sui-form demo9" style="display: inline-block;">
                <input type="text" value="2014-03-02 12:48">
            </form>

            <input type="button" value="删除" class="del_btn" style="background-color: #f31e1e; color: white;">
        </div>

    </div>
    <div class="add-time" id="addFestivalBtn">
        <i class="iconfont">&#xe60c</i>添加节假日时间
    </div>
</div>

<script id="choose-term-item" type="text/template">
    <%_.each(schoolCheckTimeSets, function(schoolCheckTimeSet) {%>
    <li role="presentation"><a role="menuitem" tabindex="-1" href="javascript:void(0);" style="font-weight:900"><%=schoolCheckTimeSet.name%></a></li>
    <%});%>
</script>

<script id="look-time-everyday" type="text/template">
    <%_.each(days,function(day,index){%>
    <% if(day.status==1){%>
    <div ><%= status[index]%><div style="width:70px;display:inline-block;"></div><%= day.quantum%></div><br>
    <%}});%>
</script>

<script id="look-item-festival" type="text/template">
    <%_.each(festivals,function(festival){
        var startDate = new Date(festival.start);
        var endDate = new Date(festival.end);
    %>
    <div style="float:left;padding-bottom:10px;width:100px;"><%=festival.name%></div>
    <%=formatDate(startDate)%>
    <div style="width:40px;display:inline-block;"></div>至<div style="width:40px;display:inline-block;"></div>
    <%=formatDate(endDate)%>
    </div>
    <div style="clear:both;"></div>
    <%});%>
</script>

<script id="edit-time-week" type="text/template">
    <!--传入checkTimeSet和weekLabels,quantumLabels数组-->
    <div class="set_time" id="set_time_weekdays">
        <div class="data">
            <p style="margin:0;padding-left:10px;display:inline-block;"><%=weekLabels[0]%>:</p>
        </div>
        <% _.each(checkTimeSet.weekdays,function(day,index){%>
        <div class="set_time-item">
            <form class="sui-form"  style="display: inline-block;">
                <% if (day.status==0){%>
                <label class="checkbox-pretty inline ">

                    <input type="checkbox" class="input_checkbox"><span style="margin-right:30px;"><%=quantumLabels[index]%></span>

                </label>
                <%}else{%>
                <label class="checkbox-pretty inline checked">

                    <input type="checkbox" checked class="input_checkbox"><span style="margin-right:30px;"><%=quantumLabels[index]%></span>

                </label>
                <%}%>
                <input value="<%=day.startTimeStr%>" type="text" class="from-time" data-toggle="timepicker" style="width:90px;text-align: center;">
            </form> -

            <form class="sui-form"  style="display: inline-block;">
                <input value="<%=day.endTimeStr%>" type="text" class="to-time" data-toggle="timepicker" style="width:90px;text-align: center;">
            </form>
        </div>
        <%});%>
    </div>
    <div class="set_time" id="set_time_sat">
        <div class="data">
            <p style="margin:0;padding-left:10px;display:inline-block;"><%=weekLabels[1]%>:</p>
        </div>
        <% _.each(checkTimeSet.saturday,function(day,index){%>
        <div class="set_time-item">
            <form class="sui-form"  style="display: inline-block;">
                <% if (day.status==0){%>
                <label class="checkbox-pretty inline ">

                    <input type="checkbox" class="input_checkbox"><span style="margin-right:30px;"><%=quantumLabels[index]%></span>

                </label>
                <%}else{%>
                <label class="checkbox-pretty inline checked">

                    <input type="checkbox" checked class="input_checkbox"><span style="margin-right:30px;"><%=quantumLabels[index]%></span>

                </label>
                <%}%>
                <input value="<%=day.startTimeStr%>" type="text" class="from-time" data-toggle="timepicker" style="width:90px;text-align: center;">
            </form> -

            <form class="sui-form"  style="display: inline-block;">
                <input value="<%=day.endTimeStr%>" type="text" class="to-time" data-toggle="timepicker" style="width:90px;text-align: center;">
            </form>
        </div>
        <%});%>
    </div>
    <div class="set_time" id="set_time_sun">
        <div class="data">
            <p style="margin:0;padding-left:10px;display:inline-block;"><%=weekLabels[2]%>:</p>
        </div>
        <% _.each(checkTimeSet.sunday,function(day,index){%>
        <div class="set_time-item">
            <form class="sui-form"  style="display: inline-block;">
                <% if (day.status==0){%>
                <label class="checkbox-pretty inline ">

                    <input type="checkbox"  class="input_checkbox"><span style="margin-right:30px;"><%=quantumLabels[index]%></span>

                </label>
                <%}else{%>
                <label class="checkbox-pretty inline checked">

                    <input type="checkbox" checked class="input_checkbox"><span style="margin-right:30px;"><%=quantumLabels[index]%></span>

                </label>
                <%}%>
                <input value="<%=day.startTimeStr%>" type="text" class="from-time" data-toggle="timepicker" style="width:90px;text-align: center;">
            </form> -

            <form class="sui-form"  style="display: inline-block;">
                <input value="<%=day.endTimeStr%>" type="text" class="to-time" data-toggle="timepicker" style="width:90px;text-align: center;">
            </form>
        </div>
        <%});%>
    </div>
</script>
<script id="hol_tag_item" type="text/template">
    <%_.each(festivalTips,function(tip){%>
    <li><%=tip.name%></li>
    <%});%>
</script>

<script id="edit_hol_item" type="text/template">
    <%_.each(festivals,function(festival){%>
    <div class="hol_lump-item" >
        <input type="text" class="festival_name" value="<%=festival.name%>" style="width:70px;height:18px;padding:2px 4px;border: 1px solid #cccccc;font-size: 12px;">

        <form class="sui-form demo8" style="margin-left: 20px;display: inline-block;">
            <input type="text" class="festival_fromDate" value="<%=festival.fromDateTime%>">
        </form>


        至

        <form class="sui-form demo9" style="display: inline-block;">
            <input type="text" class="festival_toDate" value="<%=festival.toDateTime%>">
        </form>

        <input type="button" value="删除" class="del_btn">
    </div>
    <%});%>
</script>
<script id="add_hol_item" type="text/template">
    <div class="hol_lump-item" >
        <input type="text" value="<%=festival.name%>" style="width:70px;height:18px;padding:2px 4px;border: 1px solid #cccccc;font-size: 12px;">

        <form class="sui-form demo8"  style="margin-left: 20px;display: inline-block;">
            <input type="text" value="<%=festival.fromDateTime%>">
        </form>


        至

        <form class="sui-form demo9"  style="display: inline-block;">
            <input type="text" value="<%=festival.toDateTime%>">
        </form>

        <input type="button" value="删除" class="del_btn">
    </div>
</script>
<script type="application/javascript" src="/lib/jquery.min.js"></script>
<script type="application/javascript" src="/lib/sui.min.js"></script>
<script type="application/javascript" src="/lib/underscore-min.js"></script>

<script type="application/javascript" src="/public/js/util.js"></script>
<script type="application/javascript" src="/public/js/ui.js"></script>
<script type="application/javascript" src="/modules/leader/js/leader.js"></script>
<script type="application/javascript" src="/modules/leader/js/query.js"></script>
<script>
    $(document).ready(function(){


        var request = new Request('/leader/timesetting');

        var  schoolCheckTimeSets=[];
        var currentGradeIndex = 0;

        var festivalTips=[];
        var festivals=[];


        $('#unvisiablePicker').datepicker({
            timepicker:true,
            autoclose: false
        });
        /**
         * 判断这一天是否全部未勾选
         * */
        function isAllUnselected(_days){
            if (!_days||_days.length==0){
                return true;
            }
            var allUnselected=true;
            _.each(_days, function (quantum) {
                if (quantum.status==1){
                    allUnselected=false;
                }
            })
            return allUnselected;
        }

        /**
         * 生成当前状态的CheckTimeSet
         * */
        function getCurrentCheckTimeSet(_checkTimeSet){
            var currentCheckTimeSet= _.clone(_checkTimeSet);

            for (var i=0;i<3;i++){
                if ($('#set_time_weekdays .set_time-item:eq('+i+') .checkbox-pretty').hasClass('checked')){
                    currentCheckTimeSet.weekdays[i].status=1
                }else{
                    currentCheckTimeSet.weekdays[i].status=0
                }
            }

            for (i=0;i<3;i++){
                if ($('#set_time_sat .set_time-item:eq('+i+') .checkbox-pretty').hasClass('checked')){
                    currentCheckTimeSet.saturday[i].status=1
                }else{
                    currentCheckTimeSet.saturday[i].status=0
                }
            }

            for (i=0;i<3;i++){
                if ($('#set_time_sun .set_time-item:eq('+i+') .checkbox-pretty').hasClass('checked')){
                    currentCheckTimeSet.sunday[i].status=1
                }else{
                    currentCheckTimeSet.sunday[i].status=0
                }
            }




            parseTimeFromInput(currentCheckTimeSet.weekdays,'#set_time_weekdays');
            parseTimeFromInput(currentCheckTimeSet.saturday,'#set_time_sat');
            parseTimeFromInput(currentCheckTimeSet.sunday,'#set_time_sun');

            return currentCheckTimeSet
        }

        /**
         * 生成当前状态的festivals
         * */
        function getCurrentFestivals(_festivals){
            var oldFestivals= _.clone(_festivals);
            var festivalCount=oldFestivals.length;
            for (var i=0;i<festivalCount;i++){
                oldFestivals[i].name=$('#edit_hol_list .hol_lump-item:eq('+i+') .festival_name').val();
                oldFestivals[i].start=standardDatetime('#edit_hol_list .hol_lump-item:eq('+i+') .festival_fromDate');
                oldFestivals[i].end=standardDatetime('#edit_hol_list .hol_lump-item:eq('+i+') .festival_toDate');
                if (!oldFestivals[i].start || !oldFestivals[i].end) {
                    alert('时间为空！');
                    return null;
                }
            }
            return oldFestivals;


        }


        /**
         * input值格式化
         * */
        function parseTimeFromInput(_days,_setTime){
            for (var i=0;i<3;i++){
                console.log(_setTime+' .set_time-item:eq('+i+') .from-time');
                var fromStr=($(_setTime+' .set_time-item:eq('+i+') .from-time').val()).toString();
                _days[i].startHour=parseInt(fromStr.split(':')[0],10);
                _days[i].startMinute=parseInt(fromStr.split(':')[1],10);
                var toStr=($(_setTime+' .set_time-item:eq('+i+') .to-time').val()).toString();
                _days[i].endHour=parseInt(toStr.split(':')[0],10);
                _days[i].endMinute=parseInt(toStr.split(':')[1],10);
            }


        }
        /**
         * 每周考勤时间浏览模式的更新
         * @type {string[]}
         */
        function updateAllTimeLabels(){

            var dayStatus = ['上午','下午','晚上'];
            var $timeLabel_mon_to_fri= _.template($("#look-time-everyday").html());
            $("#look_mon_to_fri").html($timeLabel_mon_to_fri({
                days:schoolCheckTimeSets[currentGradeIndex].checkTimeSet.weekdays,
                status:dayStatus
            }));
            if (isAllUnselected(schoolCheckTimeSets[currentGradeIndex].checkTimeSet.weekdays)){
                $('#look_title_weekdays').hide()
            }else{
                $('#look_title_weekdays').show()
            }

            var $timeLabel_sat=_.template($("#look-time-everyday").html());
            $('#look_sat').html($timeLabel_sat({
                days:schoolCheckTimeSets[currentGradeIndex].checkTimeSet.saturday,
                status:dayStatus
            }));
            if (isAllUnselected(schoolCheckTimeSets[currentGradeIndex].checkTimeSet.saturday)){
                $('#look_title_sat').hide()
            }else{
                $('#look_title_sat').show()
            }

            var $timeLabel_sun=_.template($("#look-time-everyday").html());
            $('#look_sun').html($timeLabel_sun({
                days:schoolCheckTimeSets[currentGradeIndex].checkTimeSet.sunday,
                status:dayStatus
            }));
            if (isAllUnselected(schoolCheckTimeSets[currentGradeIndex].checkTimeSet.sunday)){
                $('#look_title_sun').hide()
            }else{
                $('#look_title_sun').show()
            }
        }

        /**
         * 更新年级的下拉菜单
         */
        function updateDropMenu(){
            var $choose_term_item = _.template($("#choose-term-item").html());
            $("#choose-term-drop-look").html($choose_term_item({
                schoolCheckTimeSets: schoolCheckTimeSets
            }));
            $("#choose-term-drop-look li:first").addClass('active');

            $('.current_term_label').text(schoolCheckTimeSets[0].name);
            $("#choose-term-drop-look li").click(function(){
                var index =  $(this).index();
                $('.current_term_label').text(schoolCheckTimeSets[index].name);
                $("#choose-term-drop-look li").removeClass('active');
                $(this).addClass('active');
                currentGradeIndex=index;
                updateAllTimeLabels();

            });

        }

        /**
         * 节日在浏览状态的更新
         */
        function updateAllFestivals(data){
            var $festivalItem = _.template($('#look-item-festival').html());
            var noContentHTML='<div class="no-content no-icon"> <div class="warning">暂无内容,点编辑添加</div> </div>';
            if (!data.festivals||data.festivals.length==0){
                $('#look_festivals').html(noContentHTML);
            }else {
                $('#look_festivals').html($festivalItem({
                    festivals:data.festivals
                }));
            }

        }

        /**
         * 生成时间段
         */
        function updateQuantums(){
            _.each(schoolCheckTimeSets, function (schoolCheckTimeSet) {
                stringfiQuantum(schoolCheckTimeSet.checkTimeSet);
            })
        }

        /**
         * 初始化数据
         * */
        function initSchoolCheckTimeSets(data){
            var allGrade = {
                name:'全部',
                checkTimeSet:data.schoolCheckTimeSet
            };

            schoolCheckTimeSets.push(allGrade);
            for (var i=0;i<data.grades.length;i++){
                schoolCheckTimeSets.push(data.grades[i]);
            }
        }

        /**
         * 初始化节日建议相关
         * */
        function initFestival(data){
            festivalTips=data.festivalTips;
            festivals=data.festivals;
        }




        /**
         * 格式化时间
         * */
        function standardDatetime(filter){
            if ($(filter).val()) {
                var datetime=$(filter).datepicker('getDate');
                return datetime;
            }
            return null;
        }

        /**
         * 解析标准格式时间
         * */
        function parseDatetime(datetime){
            var date = new Date(datetime);
            $('#unvisiablePicker').datepicker('update',date);
            return $('#unvisiablePicker').val();

        }

        /**
         * 保存时间设置
         * */
        function saveTimeSet(successCallback){
            var checkTimeSet=getCurrentCheckTimeSet(schoolCheckTimeSets[currentGradeIndex].checkTimeSet);

            var postRequest = new Request('/checktimeset/'+checkTimeSet.id+'/update');
            console.log(checkTimeSet);
            postRequest.postJSON({
                'checkTimeSet':checkTimeSet
            },function(res){
                console.log(res);
                if (!res.successful){
                    alert('提交失败');
                    return;
                }
                var schoolCheckTimeSet = {
                    name:schoolCheckTimeSets[currentGradeIndex].name,
                    checkTimeSet:res.data.checkTimeSet
                };
                schoolCheckTimeSets[currentGradeIndex]=schoolCheckTimeSet;
                updateQuantums();
                updateAllTimeLabels();

                successCallback();
            },function(err){
                console.log(err);
                alert('网络连接出现问题');
            })

        }

        function checkFestival(_festivals){
            for (var i=0;i<_festivals.length;i++ ){
                var festival=_festivals[i];
                if (!festival.start||!festival.end){
                    return false
                }
            }
            return true;
        }

        /**
         * 保存节日
         * */
        function saveFestivalSet(successCallback){
            var postRequest  = new Request('/school/festival/update');
            var currentFestivals=getCurrentFestivals(festivals);
            if (!currentFestivals) {
                return;
            }

            postRequest.postJSON({
                festivals:currentFestivals
            }, function (res) {
                console.log(res);
                if(!res.successful){
                    alert('提交失败');
                    return;
                }
                if (!checkFestival(res.data.festivals)){
                    alert('请填充')
                }
                updateAllFestivals(res.data);
                successCallback();



            }, function (err) {
                alert('网络错误')
            })
        }


        /**
         * 更新编辑模式下的时间设置
         * */
        function updateEditWeek(){
            var $editTimeWeek = _.template($('#edit-time-week').html());
            $('#edit_week').html($editTimeWeek({
                checkTimeSet:schoolCheckTimeSets[currentGradeIndex].checkTimeSet,
                weekLabels:['周一至周五','周六','周日'],
                quantumLabels:['上午','下午','晚上']
            }))

        }

        /**
         * 更新编辑模式下的节假日
         * */
        function updateEditFestival(){
            var $hol_tags= _.template($('#hol_tag_item').html());
            $('#hol_tags').html($hol_tags({
                festivalTips:festivalTips
            }));

            _.each(festivals, function (_festival) {
                _festival.fromDateTime=parseDatetime(_festival.start);
                _festival.toDateTime=parseDatetime(_festival.end);

            })
            var $hol_edit_list = _.template($('#edit_hol_item').html());
            $('#edit_hol_list').html($hol_edit_list({
                festivals:festivals
            }))

            $('.demo8 input').datepicker({
                timepicker: true,
                autoclose: false
            });
            $('.demo9 input').datepicker({
                timepicker: true,
                autoclose: false
            });



        }


        function addFestivalItem(_festival){
            festivals.push(_festival);
            updateEditFestival();
        }
        /**
         * 时间设置点编辑
         * */
        $("#stu_btn").click(function(){



            updateEditWeek();
            $(".plan.look").css("display","none");
            $(".plan.convert").css("display","block");


        });

        /**
         * 时间设置点保存
         * */
        $("#s1_btn").click(function(){
            function changeFrame () {
                $(".plan.convert").css("display","none");
                $(".plan.look").css("display","block");
            }
            saveTimeSet(changeFrame);


        });

        /**
         * 节假日点编辑
         */
        $("#hol_btn").click(function(){
            updateEditFestival();
            $(".holiday.look").css("display","none");
            $(".holiday.convert").css("display","block");
        });

        /**
         * 点击添加建议节日
         */
        $(document).on('click', '#hol_tags li', function () {
            var tipIndex = $(this).index();
            var festival = {
                name:festivalTips[tipIndex].name,
                start:festivalTips[tipIndex].start,
                end:festivalTips[tipIndex].end,
                status:1
            }
            addFestivalItem(festival);

        });

        /**
         * 点击保存节假日
         * */
        $("#s2_btn").click(function(){
            function changeFrame(){
                $(".holiday.convert").css("display","none");
                $(".holiday.look").css("display","block");
            }
            saveFestivalSet(changeFrame);

        });


        /**
         * 点击了删除节假日
         */
        $(document).on('click', '.del_btn', function(){
            var delItemIndex=$(this).parent().index();
            festivals.splice(delItemIndex,1)

            updateEditFestival();

        });

        /**
         * 添加一条空白假日
         */
        $(document).on('click','#addFestivalBtn', function () {
            var festival = {
                name:'自定义假日',
                start: Date.now(),
                end: Date.now(),
                status:1
            }
            addFestivalItem(festival);
        });




        /**
         * 标准化时间段
         * @param _checkTimeSet
         */
        function stringfiQuantum(_checkTimeSet){
            function stringfiQuantumByDays(_days){
                for (var i=0;i<_days.length;i++){
                    var day  =_days[i];
                    day.startTimeStr = paddingZero(day.startHour,2)+':'+paddingZero(day.startMinute,2);
                    day.endTimeStr = paddingZero(day.endHour,2)+':'+paddingZero(day.endMinute,2);
                    day.quantum = paddingZero(day.startHour,2)+':'+paddingZero(day.startMinute,2)+'-'
                            +paddingZero(day.endHour,2)+':'+paddingZero(day.endMinute,2);
                }
            }
            stringfiQuantumByDays(_checkTimeSet.weekdays);
            stringfiQuantumByDays(_checkTimeSet.saturday);
            stringfiQuantumByDays(_checkTimeSet.sunday);

        }


        request.getJSON(function (data) {
            if (!data.successful){
                alert('获取数据失败!');
                return;
            }
            initSchoolCheckTimeSets(data);
            updateQuantums();
            updateAllTimeLabels();
            updateDropMenu();

            updateAllFestivals(data);
            initFestival(data);
        }, function (err) {
            alert('联网失败!');
        })

    });
</script>
